package com.zxtyshangjia.zxtyjms.business.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zxtyshangjia.zxtyjms.R;
import com.zxtyshangjia.zxtyjms.base.BaseFragment;
import com.zxtyshangjia.zxtyjms.business.activity.AddShangjiaActivity;
import com.zxtyshangjia.zxtyjms.business.adapter.ShangjiaAdapter;
import com.zxtyshangjia.zxtyjms.business.bean.ShangjiaBean;
import com.zxtyshangjia.zxtyjms.business.bean.ShangjiaList;
import com.zxtyshangjia.zxtyjms.order.bean.ClassBean;
import com.zxtyshangjia.zxtyjms.order.bean.ClassifyBean;
import com.zxtyshangjia.zxtyjms.order.fragment.TwoFragment;
import com.zxtyshangjia.zxtyjms.utils.Api;
import com.zxtyshangjia.zxtyjms.utils.SpUtils;
import com.zxtyshangjia.zxtyjms.utils.ToastUtil;
import com.zxtyshangjia.zxtyjms.utils.WheelViewPopwindow;
import com.zxtyshangjia.zxtyjms.utils.refresh.BGANormalRefreshViewHolder;
import com.zxtyshangjia.zxtyjms.utils.refresh.BGARefreshLayout;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;


/**
 * Created by lv
 * 商家
 */

public class ThreeFragment extends BaseFragment {
    private View threeView;

    /**
     * 全部 有点击事件  class_id 传空
     */
    private TextView mAllOrderTv;

    /**
     * 前面的时间   有点击事件
     */
    private TextView mFrontTimeTv;

    /**
     * 后面的时间 有点击事件
     */
    private TextView mBehindTimeTv;

    /**
     * 分类 有点击事件
     */
    private TextView mClassOlderTv;

    /**
     * 筛选 有点击事件
     */
    private TextView mFilterOrderTv;

    /**
     *  商家数
     */
    private TextView mNumOfShangjia;

    /**
     * 商家列表
     */
    private ListView mSjListLV;

    /**
     *  添加商家
     */
     private TextView mAddShangjia;

    /**
     *  下拉刷新 上拉加载布局
     */
    private BGARefreshLayout mSjRefresh;


    /**
     * 判断是下拉刷新还是加载更多
     */
    private boolean refreshOrLoad = true;
    private int startIndex = 1;

    /**
     * 下拉刷新加载更多 头脚布局选择
     */
    private BGANormalRefreshViewHolder refreshViewHolder;

    /**
     * 适配器
     */
    private ShangjiaAdapter sjListAdapter;

    private Object object;

    /**
     * 日历
     */
    private DatePicker dpPicker;

    /**
     *  和后端交互的参数
     */
    private String e_id;
    private String start_time = "";
    private String end_time = "";
    private String class_id = "";

    private int index;

    /**
     * 订单列表数组
     */

    private ShangjiaBean bean;

    private ArrayList<ShangjiaList> sjList = new ArrayList<>();

    /**
     *  分类数组
     */

    private ClassBean cBean;

    private ArrayList<ClassifyBean> classList = new ArrayList<>();

    private List<String> className = new ArrayList<>();

    /**
     * 是否选择了起 / 止时间
     */
    private Boolean isFront = false;
    private Boolean isBehind = false;

    /**
     * 是否选择了分类
     */
    private Boolean isClass = false;

    private int timeType;
    /*
     * 当前年
     */
    int year = 0;
    /**
     * 当前月
     */
    int mMonth = 0;

    int dayOfMonth = 0;

    private String time1;
    private String time2;
    private Boolean isRight = false;


    /**
     * 点击侦听
     */

    private View.OnClickListener mClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            if(view.getId() == mAllOrderTv.getId()){
                //全部

                isFront = false;
                isBehind = false;
                isClass = false;
                mFrontTimeTv.setText("月-日");
                mBehindTimeTv.setText("月-日");
                mClassOlderTv.setText("分类");
                class_id = "";
                start_time = "";
                end_time = "";

                mSjRefresh.beginRefreshing();
                mFilterOrderTv.setTextColor((mActivity.getResources().getColor(R.color.gray_999999)));
                mFilterOrderTv.setBackgroundResource(R.drawable.shape_bg_tv);


                dpPicker.setVisibility(View.GONE);
                mSjListLV.setVisibility(View.VISIBLE);

            }else if(view.getId() == mFrontTimeTv.getId()){
                //开始时间

                dpPicker.setVisibility(View.VISIBLE);
                mSjListLV.setVisibility(View.GONE);
                timeType = 1;

            }else if(view.getId() == mBehindTimeTv.getId()){
                //结束时间

                dpPicker.setVisibility(View.VISIBLE);
                mSjListLV.setVisibility(View.GONE);
                timeType = 2;


            }else if(view.getId() == mClassOlderTv.getId()){
                //分类

                dpPicker.setVisibility(View.GONE);
                mSjListLV.setVisibility(View.VISIBLE);

                new WheelViewPopwindow(getActivity(), className , mClassOlderTv, new WheelViewPopwindow.OnSuccessClick() {
                    @Override
                    public void onSuccessClick(int position, String content) {

                        Log.e("position & content ==",position + "  " + content);

                        isClass = true;
                        if (position == 0) {
                            class_id = "";
                        } else {
                            class_id = classList.get(position - 1).class_id;
                            Log.e("classList i name =====", classList.get(position - 1).name);
                        }

                        Log.e("class_id =====", class_id);
                        mFilterOrderTv.setTextColor((mActivity.getResources().getColor(R.color.mainColor)));
                        mFilterOrderTv.setBackgroundResource(R.drawable.shape_bg_tv_pass);


                    }
                }).showPop();

            }else if(view.getId() == mFilterOrderTv.getId()){
                //点击进行筛选

                dpPicker.setVisibility(View.GONE);
                mSjListLV.setVisibility(View.VISIBLE);

                if(Integer.parseInt(time1) > Integer.parseInt(time2)){
                    isRight = false;
                }else {
                    isRight = true;
                }

                if ((isFront && isBehind && isRight) || isClass) {

                    mSjRefresh.beginRefreshing();

                } else {
                    if(!isRight){
                        ToastUtil.showToast("开始时间不能在结束时间之前哦");
                    }else {
                        ToastUtil.showToast("请您选择筛选条件");
                    }
                }

            }else if(view.getId() == mAddShangjia.getId()){

                //点击跳转添加商家页
                Intent intent = new Intent(mActivity, AddShangjiaActivity.class);
                mActivity.startActivity(intent);


            }

        }
    };

    /**
     * 下拉刷新、上拉加载监听器
     */
    private BGARefreshLayout.BGARefreshLayoutDelegate refreshLayoutDelegate = new BGARefreshLayout.BGARefreshLayoutDelegate() {
        @Override
        public void onBGARefreshLayoutBeginRefreshing(BGARefreshLayout refreshLayout) {
            startIndex = 1;
            refreshOrLoad = true;
            initSjAbout(startIndex);   //初始化订单相关  包括订单数/收益/列表
        }

        @Override
        public boolean onBGARefreshLayoutBeginLoadingMore(BGARefreshLayout refreshLayout) {
            refreshOrLoad = false;
            initSjAbout(++startIndex);
            return true;  //此处一定要返回true，否则不会出现正在加载的窗口;
        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (threeView == null) {
            threeView = View.inflate(mActivity, R.layout.fragment_three, null);
        }

        e_id = SpUtils.getInstance(mActivity).getString("e_id","");

        bindViews();
        bindListener();
        initData();
        mSjRefresh.beginRefreshing();
        return threeView;
    }

    private void bindViews() {
        //在此绑定view

        mAllOrderTv = (TextView) threeView.findViewById(R.id.all_sj_tv);
        mFrontTimeTv = (TextView) threeView.findViewById(R.id.sj_begin_time_tv);
        mBehindTimeTv = (TextView) threeView.findViewById(R.id.sj_end_time_tv);
        mClassOlderTv = (TextView) threeView.findViewById(R.id.sj_class_tv);
        mFilterOrderTv = (TextView) threeView.findViewById(R.id.sj_filter_tv);

        mAddShangjia = (TextView) threeView.findViewById(R.id.sj_add_tv);

        mSjListLV = (ListView) threeView.findViewById(R.id.sj_list_lv);
        mSjRefresh = (BGARefreshLayout) threeView.findViewById(R.id.sj_refresh);

        dpPicker = (DatePicker) threeView.findViewById(R.id.sj_dpPicker);

        View view = LayoutInflater.from(mActivity).inflate(R.layout.sj_list_header, null);
        mNumOfShangjia = (TextView) view.findViewById(R.id.num_sj_tv);
        mSjListLV.addHeaderView(view);

    }

    private void bindListener() {
        //在此绑定监听器

        //在此绑定监听器
        mAllOrderTv.setOnClickListener(mClickListener);
        mFrontTimeTv.setOnClickListener(mClickListener);
        mBehindTimeTv.setOnClickListener(mClickListener);
        mClassOlderTv.setOnClickListener(mClickListener);
        mFilterOrderTv.setOnClickListener(mClickListener);
        mAddShangjia.setOnClickListener(mClickListener);

        //初始化监听事件
        mSjRefresh.setDelegate(refreshLayoutDelegate);

    }

    private void initData() {
        //在此处理数据
//
//        if(e_id.equals("5")){
//            mAddShangjia.setVisibility(View.GONE);
//        }

        initClassList();  //初始化分类列表

        initDate();//初始化 日期时间

        initList();  //初始化订单列表

    }

    private void initList() {

        refreshViewHolder = new BGANormalRefreshViewHolder(getContext(), true, true);
        mSjRefresh.setRefreshViewHolder(refreshViewHolder);
        sjListAdapter = new ShangjiaAdapter(mActivity, new ArrayList<ShangjiaList>());
        mSjListLV.setAdapter(sjListAdapter);

    }


    /**
     * 初始化信息时间
     */
    private void initDate() {
        Calendar calendar= Calendar.getInstance();
        // 获得日历对象
        Calendar c = Calendar.getInstance();

        year = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH) + 1;

        dpPicker.init(year, mMonth, dayOfMonth, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                ThreeFragment.this.year = year;
                ThreeFragment.this.mMonth = monthOfYear+1;
                ThreeFragment.this.dayOfMonth = dayOfMonth;

                Log.e("dayOfMonth=========",dayOfMonth+"");
                dpPicker.setVisibility(View.GONE);
                mSjListLV.setVisibility(View.VISIBLE);
                if(ThreeFragment.this.mMonth < 10){

                    if(ThreeFragment.this.dayOfMonth <10){
                        if(timeType == 1){
                            mFrontTimeTv.setText("0" + ThreeFragment.this.mMonth + "-0" + ThreeFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = ThreeFragment.this.year +"-"+ mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ",start_time);
                            time1 = ThreeFragment.this.year + "0" + ThreeFragment.this.mMonth + "0" + ThreeFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        }else {
                            mBehindTimeTv.setText("0" + ThreeFragment.this.mMonth + "-0" + ThreeFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = ThreeFragment.this.year+"-"+ mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ",end_time);
                            time2 = ThreeFragment.this.year + "0" + ThreeFragment.this.mMonth + "0" + ThreeFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }
                    }else {

                        if(timeType == 1){
                            mFrontTimeTv.setText("0" + ThreeFragment.this.mMonth + "-" + ThreeFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = ThreeFragment.this.year +"-"+ mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ",start_time);
                            time1 = ThreeFragment.this.year + "0" + ThreeFragment.this.mMonth +""+ ThreeFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        }else {
                            mBehindTimeTv.setText("0" + ThreeFragment.this.mMonth + "-" + ThreeFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = ThreeFragment.this.year +"-"+ mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ",end_time);
                            time2 = ThreeFragment.this.year + "0" + ThreeFragment.this.mMonth +""+  ThreeFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }

                    }


                }else {

                    if(ThreeFragment.this.dayOfMonth <10){
                        if(timeType == 1){
                            mFrontTimeTv.setText( ThreeFragment.this.mMonth + "-0" + ThreeFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = ThreeFragment.this.year +"-"+ mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ",start_time);
                            time1 = ThreeFragment.this.year  +""+ ThreeFragment.this.mMonth + "0"+ ThreeFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        }else {
                            mBehindTimeTv.setText( ThreeFragment.this.mMonth + "-0" + ThreeFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = ThreeFragment.this.year +"-"+ mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ",end_time);
                            time2 = ThreeFragment.this.year +"" + ThreeFragment.this.mMonth + "0"+ ThreeFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }
                    }else {

                        if(timeType == 1){
                            mFrontTimeTv.setText( ThreeFragment.this.mMonth + "-" + ThreeFragment.this.dayOfMonth);
                            isFront = true;
                            start_time = ThreeFragment.this.year +"-"+ mFrontTimeTv.getText().toString();
                            Log.e("start_time ===== ",start_time);
                            time1 = ThreeFragment.this.year +"" + ThreeFragment.this.mMonth + ""+ ThreeFragment.this.dayOfMonth;
                            Log.e("time1 ===== ", time1);
                        }else {
                            mBehindTimeTv.setText( ThreeFragment.this.mMonth + "-" + ThreeFragment.this.dayOfMonth);
                            isBehind = true;
                            end_time = ThreeFragment.this.year +"-"+ mBehindTimeTv.getText().toString();
                            Log.e("end_time ===== ",end_time);
                            time2 = ThreeFragment.this.year +"" + ThreeFragment.this.mMonth + ""+ ThreeFragment.this.dayOfMonth;
                            Log.e("time2 ===== ", time2);
                        }

                    }

                }

                if(isFront && isBehind){
                    mFilterOrderTv.setTextColor((mActivity.getResources().getColor(R.color.mainColor)));
                    mFilterOrderTv.setBackgroundResource(R.drawable.shape_bg_tv_pass);
                }

            }
        });

    }


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    mSjRefresh.endRefreshing();
                    break;
                case 1:
                    mSjRefresh.endLoadingMore();
                    break;
            }
        }
    };


    /**
     * 初始化订单相关  包括订单数/收益/列表
     */
    private void initSjAbout(int startIndex) {

        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(Api.CASH_SHOPLIST + "?p=" + startIndex + "&e_id=" + e_id + "&start_time=" + start_time
                        + "&end_time=" + end_time + "&class_id=" + class_id)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {
                    Log.e("response =========", String.valueOf(response));
                    Class responseClass = ShangjiaBean.class;
                    final String res = response.body().string();
                    Log.e("res =========", res);
                    object = new Gson().fromJson(res, responseClass);

                } catch (Exception e) {
                    Log.e("Exception e=======", "error");

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            object = null;
                            sjList.clear();
                            mSjRefresh.endRefreshing();
                        }
                    });
                }

                if (object != null && object instanceof ShangjiaBean) {
                    bean = (ShangjiaBean) object;
                    if (bean.flag.equals("success")) {
                        //获取成功

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mNumOfShangjia.setText(bean.data.shop_num);
                            }
                        });


                        if (refreshOrLoad) {
                            //下拉刷新
                            if (bean.data.list == null){
                                sjList.clear();
                            }else if (bean.data.list.size() > 0) {
                                sjList.clear();
                                sjList.addAll(bean.data.list);
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    sjListAdapter.refreshData(sjList, refreshOrLoad);
                                    Message msg = new Message();
                                    msg.what = 0;
                                    mHandler.sendMessage(msg);
                                }
                            });

                        } else {
                            //上拉加载更多
                            if (bean.data == null) {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        refreshViewHolder.hideLoadingMoreImg();
                                        refreshViewHolder.updateLoadingMoreText("没有更多了");
                                        Message msg = new Message();
                                        msg.what = 1;
                                        mHandler.sendMessageDelayed(msg, 2000);
                                    }
                                });
                            } else {
                                if(bean.data.list == null){
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            refreshViewHolder.hideLoadingMoreImg();
                                            refreshViewHolder.updateLoadingMoreText("没有更多了");
                                            Message msg = new Message();
                                            msg.what = 1;
                                            mHandler.sendMessageDelayed(msg, 2000);
                                        }
                                    });
                                }else {
                                    sjList.addAll(bean.data.list);
                                    getActivity().runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            sjListAdapter.refreshData(sjList, refreshOrLoad);
                                            refreshViewHolder.showLoadingMoreImg();
                                            refreshViewHolder.updateLoadingMoreText("正在加载...");
                                            Message msg = new Message();
                                            msg.what = 1;
                                            mHandler.sendMessageDelayed(msg, 2000);
                                        }
                                    });
                                }
                            }
                        }
                    } else {
                        ToastUtil.showToast(bean.message);
                        if (refreshOrLoad) {
                            Message msg = new Message();
                            msg.what = 0;
                            mHandler.sendMessage(msg);
                        } else {
                            Message msg = new Message();
                            msg.what = 1;
                            mHandler.sendMessageDelayed(msg, 2000);
                        }
                    }
                }
            }
        });


    }


    /**
     * 初始化分类列表
     */
    private void initClassList() {


        //创建okHttpClient对象
        OkHttpClient mOkHttpClient = new OkHttpClient();
        //创建一个Request
        final Request request = new Request.Builder()
                .url(Api.CASH_AGENT + "?e_id=" + e_id)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                //解析返回的结果
                try {
                    Log.e("=========response", String.valueOf(response));
                    Class responseClass = ClassBean.class;
                    final String res = response.body().string();
                    Log.e("=========res", res);
                    object = new Gson().fromJson(res, responseClass);
                } catch (Exception e) {
                    Log.e("=======", "error");
                    return;
                }
                if (object != null && object instanceof ClassBean) {
                    cBean = (ClassBean) object;
                    if (cBean.flag.equals("success")) {

                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                classList.addAll(cBean.data.classify);

                                if(classList.size() > 0){
                                    mClassOlderTv.setVisibility(View.VISIBLE);
                                    className.add("全部");
                                    for(int i = 0 ; i < classList.size();i++){
                                        className.add(classList.get(i).name);
                                    }
                                }else {
                                    mClassOlderTv.setVisibility(View.GONE);
                                }

                                Log.e("classList =======",classList.toString());


                            }
                        });

                    }
                }
            }
        });
    }



    @Override
    protected void lazyLoad() {

    }

    @Override
    public void onClick(View view) {

    }
}
